<template>
  <div v-if="vipDetail" v-loading="loading" class="vip-detail">
    <!-- 头部 -->
    <div class="vip-info">
      <div class="app-main-top-box">
        <div class="title">会员详情</div>
        <!-- 按钮组 -->
        <div>
          <el-dropdown size="small" split-button type="primary">
            会员操作
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="!$store.getters.banBtnList.includes('BTN_EDIT_MEMEBR')" @click.native="openEditInfo">编辑信息</el-dropdown-item>
              <el-dropdown-item v-if="!$store.getters.banBtnList.includes('BTN_CHANGE_MEMBER_BALANCE')" @click.native="openEditBalance">余额调整</el-dropdown-item>
              <el-dropdown-item
                v-if="!$store.getters.banBtnList.includes('BTN_ADD_MEMBER_POINTS') || !$store.getters.banBtnList.includes('BTN_SUBTRACT_MEMBER_POINTS')"
                @click.native="openEditPoints"
              >
                积分调整
              </el-dropdown-item>
              <!--    <el-dropdown-item-->
              <!--      v-if="!$store.getters.banBtnList.includes('BTN_GIVE_MEMBER_COUPON')"-->
              <!--      @click.native="openGiftCardCoupon(1)"-->
              <!--    >送优惠券</el-dropdown-item>-->
              <el-dropdown-item v-if="!$store.getters.banBtnList.includes('BTN_GIVE_MEMBER_COUPON')" @click.native="openGiftCardCoupon(2)">赠送卡券</el-dropdown-item>
              <el-dropdown-item v-if="!$store.getters.banBtnList.includes('BTN_CHANGE_MEMBER_CATEGORY')" @click.native="openEditCardType">
                卡类型调整
              </el-dropdown-item>
              <el-dropdown-item v-if="!$store.getters.banBtnList.includes('MCH_BTN_MEMBER_TAGS_EDIT')" @click.native="openEditLabelType">标签调整</el-dropdown-item>
              <el-dropdown-item v-if="$store.getters.businessResourceBtns.includes('MEMBER_BIND_DEVICE')" @click.native="bindService()">{{isBindSn?'换绑设备':'绑定设备'}}</el-dropdown-item>
              <el-dropdown-item v-if="!$store.getters.banBtnList.includes('BTN_DELETE_MEMBER')" @click.native="openCancelCard">会员退卡</el-dropdown-item>
              <el-dropdown-item
                v-if="!$store.getters.banBtnList.includes('MCH_BTN_MEMBER_EXPIRE_EDIT') && vipDetail.member.expireTime"
                @click.native="openEditExpireTime"
              >
                调整有效期
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
					&nbsp; &nbsp;
          <el-dropdown
            v-if="
              !$store.getters.banBtnList.includes('MCH_BTN_MGR_ENTITY_CARD') ||
                !$store.getters.banBtnList.includes('MCH_BTN_DEL_ENTITY_CARD') ||
                !$store.getters.banBtnList.includes('MCH_BTN_BIND_ENTITY_CARD')
            "
            size="small"
            split-button
            type="primary"
          >
            实体卡操作
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-if="vipDetail.entityCard && vipDetail.entityCard.status == 1 && !$store.getters.banBtnList.includes('MCH_BTN_MGR_ENTITY_CARD')"
                @click.native="editEntityCardStatus(1)"
              >
                挂失
              </el-dropdown-item>
              <el-dropdown-item
                v-if="vipDetail.entityCard && vipDetail.entityCard.status == 2 && !$store.getters.banBtnList.includes('MCH_BTN_MGR_ENTITY_CARD')"
                @click.native="editEntityCardStatus(2)"
              >
                解除挂失
              </el-dropdown-item>
              <el-dropdown-item
                v-if="
                  ((vipDetail.entityCard && vipDetail.entityCard.status == 1) || (vipDetail.entityCard && vipDetail.entityCard.status == 2)) &&
                    !$store.getters.banBtnList.includes('MCH_BTN_DEL_ENTITY_CARD')
                "
                @click.native="editEntityCardStatus(3)"
              >
                退卡
              </el-dropdown-item>
              <el-dropdown-item v-if="!$store.getters.banBtnList.includes('MCH_BTN_BIND_ENTITY_CARD')" @click.native="openEditEntityCard">绑新卡</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <ul class="info-avatar">
        <li class="avatar"><img v-if="vipDetail.customer && vipDetail.customer.headImg" :src="vipDetail.customer.headImg" alt></li>
        <li class="name-right">
          <div class="name">{{ vipDetail.member.name ? vipDetail.member.name : vipDetail.customer ? vipDetail.customer.nickName : '' }}</div>
          <div class="label-tag">
            <el-tag effect="dark" size="small">{{ vipDetail.categoryName }}</el-tag>
            <el-tag v-for="item of vipDetail.memberGroupTags" :key="item.id" effect="dark" size="small" class="label">{{ item }}</el-tag>
            <el-tag v-for="item of vipDetail.tags" :key="item.id" effect="dark" size="small" class="label">{{ item.tagName }}</el-tag>
          </div>
        </li>
        <!--        <li v-if="vipDetail.member.expireTime" class="expire-time">-->
        <!--          <span v-if="$momentMini().isBefore(vipDetail.member.expireTime)" class="app-text-color-primary">有效期至 {{ vipDetail.member.expireTime }}</span>-->
        <!--          <span v-else class="app-text-color-danger">于 {{ vipDetail.member.expireTime }} 已过期</span>-->
        <!--        </li>-->
        <!--        <li v-else class="expire-time">永久有效</li>-->
      </ul>

      <!-- 会员相关信息 -->
      <div class="info-content">
        <el-row type="flex">
          <el-col :xs="12" :sm="12" :md="12" :lg="8">
            <ul class="member-info-container">
              <li>
                <div class="label">状态</div>
                <div class="value">
                  {{ statusOption[vipDetail.member.status] }},
                  <span v-if="vipDetail.member.expireTime" class="expire-time">
                    <span v-if="$momentMini().isBefore(vipDetail.member.expireTime)" class="app-text-color-primary">
                      有效期至 {{ vipDetail.member.expireTime }}
                    </span>
                    <span v-else class="app-text-color-danger">于 {{ vipDetail.member.expireTime }} 已过期</span>
                  </span>
                  <span v-else class="expire-time">永久有效</span>
                </div>
              </li>
              <li>
                <div class="label">微信卡号</div>
                <div class="value">{{ vipDetail.member.cardNo || '无' }}</div>
              </li>
              <li>
                <div class="label">实体卡号</div>
                <div class="value">
                  {{ vipDetail.entityCard && vipDetail.entityCard.cardNo ? vipDetail.entityCard.cardNo : '无' }}
                  <span v-if="vipDetail.entityCard && vipDetail.entityCard.status == 2" class="app-text-color-danger">（已挂失）</span>
                </div>
              </li>
              <li>
                <div class="label">会员手机</div>
                <div class="value">{{ vipDetail.member.phone || '无' }}</div>
              </li>
              <li>
                <div class="label">会员邮箱</div>
                <div class="value">{{ vipDetail.memberExtendInfo.email || '无' }}</div>
              </li>
             
            </ul>
          </el-col>
          <el-col :xs="12" :sm="12" :md="12" :lg="8">
            <ul class="member-info-container">
              <li>
                <div class="label">会员性别</div>
                <div v-if="vipDetail.member.sex === 0" class="value">女</div>
                <div v-else-if="vipDetail.member.sex === 1" class="value">男</div>
                <div v-else class="value">未知</div>
              </li>
              <li>
                <div class="label">会员生日</div>
                <div class="value">{{ vipDetail.memberExtendInfo.birthday || '无' }}</div>
              </li>
              <li>
                <div class="label">身份证号</div>
                <div class="value">{{ vipDetail.memberExtendInfo.idCard || '无' }}</div>
              </li>
              <li>
                <div class="label">详细地址</div>
                <div class="value">{{ vipDetail.memberExtendInfo.address || '无' }}</div>
              </li>
              <li v-if="$store.getters.businessResourceBtns.includes('MEMBER_BIND_DEVICE')">
                <div class="label">设备SN</div>
                <div class="value">{{ vipDetail.memberDevices&&vipDetail.memberDevices[0].deviceSn || '无' }}</div>
              </li>
            </ul>
          </el-col>
          <el-col :xs="12" :sm="12" :md="12" :lg="8">
            <ul class="member-info-container">
              <li>
                <div class="label">教育背景</div>
                <div class="value">{{ vipDetail.memberExtendInfo.education || '无' }}</div>
              </li>
              <li>
                <div class="label">所在行业</div>
                <div class="value">{{ vipDetail.memberExtendInfo.work || '无' }}</div>
              </li>
              <li>
                <div class="label">兴趣爱好</div>
                <div class="value">
                  {{ vipDetail.memberExtendInfo.hobby && vipDetail.memberExtendInfo.hobby.length > 0 ? vipDetail.memberExtendInfo.hobby.join('、') : '无' }}
                </div>
              </li>
              <li>
                <div class="label">年收入</div>
                <div class="value">{{ vipDetail.memberExtendInfo.income || '无' }}</div>
              </li>
            </ul>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- tab栏 -->
    <div class="tab">
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="基础信息" name="info"><vip-info :active-name="activeName" :vip-detail="vipDetail" @getVipDetail="fetchData" /></el-tab-pane>
        <el-tab-pane label="余额记录" name="balance"><balance-record ref="recordBalance" :active-name="activeName" :vip-detail="vipDetail" /></el-tab-pane>
        <el-tab-pane label="交易记录" name="payHistory">
          <income-his ref="incomeHis" :active-name="activeName" :vip-detail="vipDetail" source-page="vipDetail" />
        </el-tab-pane>
        <!-- <el-tab-pane label="交易记录" name="consume" /> -->
        <el-tab-pane label="积分记录" name="point"><points-record ref="pointsRecord" :active-name="activeName" :vip-detail="vipDetail" /></el-tab-pane>
        <el-tab-pane label="卡券发放记录" name="couponIssue">
          <!-- <coupon-issue-record ref="couponIssue" :active-name="activeName" :vip-detail="vipDetail" /> -->
          <CardGrandHis :active-name="activeName" :vip-detail="vipDetail" />
        </el-tab-pane>
        <el-tab-pane label="核销记录" name="couponVerify"><coupon-verify-record :active-name="activeName" :vip-detail="vipDetail" /></el-tab-pane>
        <el-tab-pane label="标签历史" name="labelHistory"><label-history-record ref="labelHistory" :active-name="activeName" :vip-detail="vipDetail" /></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 余额变更弹框 -->
    <dialog-balance-edit ref="editBalance" :vip-detail.sync="vipDetail" />

    <!-- 积分变更弹框 -->
    <dialog-points-edit ref="editPoints" :vip-detail.sync="vipDetail" />

    <!-- 赠送优惠券 -->
    <dialog-gift-card-coupon ref="giftCardCoupon" :vip-detail.sync="vipDetail" />

    <!-- 更换卡 -->
    <dialog-type-edit ref="editCardType" :vip-detail.sync="vipDetail" />

    <!-- 更换标签 -->
    <dialog-label-type-edit ref="editLabelType" :vip-detail.sync="vipDetail" />

    <!-- 退卡弹框 -->
    <dialog-cancel-card ref="cancelCard" :vip-detail.sync="vipDetail" />

    <!-- 编辑会员资料 -->
    <dialog-info-edit ref="editInfo" :vip-detail.sync="vipDetail" />

    <!-- 编辑会员资料 -->
    <DialogEditEntityCard ref="editEntityCard" :vip-detail.sync="vipDetail" />

    <!-- 编辑会员有效期 -->
    <DialogEditExpireTime ref="editExpireTime" :vip-detail.sync="vipDetail" />
    <BindSncode  ref="BindSncode"/>
  </div>
</template>

<script>
import { getVipDetailById, editEntityCardOps,getMemberDeviceById } from '@/api/vip'
import {
  VipInfo,
  BalanceRecord,
  PointsRecord,
  CouponVerifyRecord,
  LabelHistoryRecord,
  DialogCancelCard,
  DialogInfoEdit,
  DialogTypeEdit,
  DialogLabelTypeEdit,
  DialogBalanceEdit,
  DialogPointsEdit,
  DialogGiftCardCoupon,
  DialogEditEntityCard,
  DialogEditExpireTime,
  CardGrandHis,
  BindSncode
} from './components'
import IncomeHis from '@/views/payCenterDir/payCenter/IncomeHis'
export default {
  components: {
    VipInfo,
    BalanceRecord,
    PointsRecord,
    CouponVerifyRecord,
    LabelHistoryRecord,
    DialogCancelCard,
    DialogInfoEdit,
    DialogTypeEdit,
    DialogLabelTypeEdit,
    DialogBalanceEdit,
    DialogPointsEdit,
    DialogGiftCardCoupon,
    DialogEditEntityCard,
    DialogEditExpireTime,
    CardGrandHis,
    IncomeHis,
    BindSncode
  },
  data() {
    return {
      // 配置
      statusOption: ['无', '正常', '已过期', '已退卡'], // 卡状态
      activeName: 'info', // tab栏默认显示
      // 状态
      loading: false,
      // 数据
      vipDetail: null,
      balanceCard: [{ name: '总余额', value: 0 }, { name: '实充余额', value: 0 }, { name: '赠送余额', value: 0 }],
      labelGroup: [], // 会员标签组,
      isBindSn:false,
    }
  },

  mounted() {
    this.fetchData()
  },

  methods: {
    /**
		 *  获取数据
		 */
    // 获取会员信息
    fetchData() {
      return new Promise((resolve, reject) => {
        this.loading = true
        const params = {}
        if (this.$route.query.hasOwnProperty('memberId')) {
          params.memberId = this.$route.query.memberId
        } else if (this.$route.query.hasOwnProperty('customerId')) {
          params.customerId = this.$route.query.customerId
        }
        getVipDetailById(params)
          .then(res => {
            if (!res.data) {
              this.$alert('会员不存在', '温馨提示', {
                confirmButtonText: '确定',
                center: true,
                roundButton: true
              })
                .then(() => {
                  window.close()
                })
                .catch(() => {
                  window.close()
                })
              return
            }
            // 判断有效期
            res.data.member.expireTime
            res.data.memberExtendInfo.hobby = res.data.memberExtendInfo.hobby ? res.data.memberExtendInfo.hobby.split(',') : []
            this.vipDetail = res.data
            resolve()
            // 余额卡片
            this.balanceCard[0].value = '￥' + this.$options.filters.parseNumberToThousands(res.data.balance + res.data.giftBalance) // 总余额
            this.balanceCard[1].value = '￥' + this.$options.filters.parseNumberToThousands(res.data.balance) // 实充余额
            this.balanceCard[2].value = '￥' + this.$options.filters.parseNumberToThousands(res.data.giftBalance) // 赠送余额
          })
          .finally(() => {
            this.loading = false
          })
          if(this.$store.getters.businessResourceBtns.includes('MEMBER_BIND_DEVICE')){
            getMemberDeviceById({memberId:this.$route.query.memberId}).then(res=>{
              if(res.code === 0){
                if(res?.data?.length>0){
                  this.isBindSn = true
                }
              }
            })
          }
         
      })
    },

    /**
		 *  按钮组
		 */
    // 编辑信息
    openEditInfo() {
      this.$refs.editInfo.open(this.balanceCard).then(() => {
        this.fetchData()
      })
    },

    // 余额更改
    openEditBalance() {
      this.$refs.editBalance.open().then(res => {
        // 刷新页面数据
        this.fetchData()
        if (this.activeName === 'balance') {
          this.$refs.recordBalance.getAccountInfo()
          this.$refs.recordBalance.fetchData()
        }
      })
    },

    // 积分更改
    openEditPoints() {
      this.$refs.editPoints.open().then(res => {
        // 刷新页面数据
        this.fetchData().then(res => {
          if (this.activeName === 'point') {
            this.$refs.pointsRecord.fetchData()
            this.$refs.pointsRecord.setCardData()
          }
        })
      })
    },

    // 更换卡
    openEditCardType() {
      this.$refs.editCardType.open().then(res => {
        // 刷新页面数据
        this.fetchData()
        this.activeName = 'info'
      })
    },

    // 更换标签
    openEditLabelType() {
      this.$refs.editLabelType.open().then(() => {
        // 刷新页面数据
        this.fetchData()
        console.log(this.activeName)
        if (this.activeName === 'labelHistory') {
          this.$refs.labelHistory.fetchData()
        }
      })
    },

    // 送优惠券
    openGiftCoupon() {
      this.$refs.giftCoupon.open()
    },

    // 赠送卡券
    openGiftCardCoupon(version) {
      this.$refs.giftCardCoupon.open(version).then(() => {
        // 刷新页面数据
        this.fetchData()
        console.log(this.activeName)
        if (this.activeName === 'couponIssue') {
          this.$refs.couponIssue.fetchData()
        }
      })
    },

    // 退卡
    openCancelCard() {
      this.$refs.cancelCard.open(this.balanceCard)
    },

    // 变更实体卡
    openEditEntityCard() {
      this.$refs.editEntityCard.open().then(res => {
        this.fetchData()
      })
    },

    // 变更实体卡状态
    editEntityCardStatus(status) {
      let str = ''
      let msg = ''
      if (status === 1) {
        str = '确定要挂失当前会员的实体卡? 挂失后对应实体卡的功能将会受限，积分、余额、折扣等所有功能将暂时不可用(不影响电子会员卡的使用)，解除挂失后卡片可正常使用。'
        msg = '挂失成功'
      } else if (status === 2) {
        str = '解除挂失后对应的实体卡片将可正常使用，请确定该卡片已被找回！点击确定按钮解除挂失！'
        msg = '解除挂失成功'
      } else if (status === 3) {
        str = '退卡后，实体卡所有功能失效(不影响电子会员卡的使用)，且退卡后只能通过绑新卡恢复。点击确定按钮完成退卡。'
        msg = '退卡成功'
      }
      this.$confirm(str, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      })
        .then(() => {
          const params = {
            memberId: this.vipDetail.member.id,
            operationType: status
          }
          this.loading = true
          editEntityCardOps(params)
            .then(res => {
              this.fetchData()
              this.$notify({
                title: '成功',
                message: msg,
                type: 'success',
                duration: 2000,
                offset: 40
              })
            })
            .catch(err => {})
            .finally(() => {
              this.loading = false
            })
        })
        .catch(err => {})
    },

    // 调整有效期
    openEditExpireTime() {
      this.$refs.editExpireTime.open().then(res => {
        this.fetchData()
      })
    },

    // 切换tab栏
    handleTabClick(tab, event) {},
    //   绑定设备
    bindService() {
      this.$refs.BindSncode.open(this.isBindSn)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.vip-detail {
	/* 会员资料 */
	.vip-info {
		padding: 24px 30px;
		border-radius: 5px 5px 0 0;
		background-color: #fff;
		.info-content {
			margin-left: 45px;
		}
		.info-avatar {
			height: 70px;
			margin-bottom: 15px;
			display: flex;
			li {
				margin-right: 10px;
			}
			.avatar {
				overflow: hidden;
				display: inline-block;
				width: 50px;
				height: 50px;
				border: 1px solid #e7e7e7;
				border-radius: 50%;
			}
			.name-right {
				display: flex;
				flex-direction: column;
				.name {
					height: 30px;
					line-height: 30px;
					font-size: 18px;
					font-weight: bold;
					color: $dark-font-color;
				}
			}
			.label-tag {
				display: flex;
				.label {
					margin-left: 10px;
				}
			}
		}
	}
}

/* 会员信息列表 */
.member-info-container {
	font-size: 14px;
	li {
		display: flex;
		margin-bottom: 10px;
		word-break: break-all;
	}
	.label {
		flex: 0 0 80px;
		color: $light-font-color;
	}
	.value {
		color: $dark-font-color;
	}
}

::v-deep {
	.el-tabs__header {
		padding-left: 30px;
		margin-bottom: 10px;
		background-color: #fff;
		border-radius: 0 0 5px 5px;
	}
	.el-tabs__nav-wrap::after {
		background-color: #fff;
	}
	.el-tabs__active-bar {
		height: 4px;
	}
}
</style>
